import asyncio
import time

from machine import Pin, UART

import network
import oled
import util

led = Pin(25, Pin.OUT)

uart = UART(0, baudrate=115200, bits=8, parity=None, stop=1, tx=Pin(0), rx=Pin(1))


async def demo_led():
    while True:
        led.value(1)
        time.sleep(0.1)
        led.value(0)
        time.sleep(0.1)

async def read_message():
    global uart
    while True:
        if uart.any():
            print("*************")
            response_bytes = uart.read(1024)
            a = util.response_bytes_to_string(response_bytes)
            response_list = a.split(',')
            print(response_list)
            if len(response_list) >2:
                oled.add_write_message(response_list[2])
            else:
                oled.add_write_message(response_list)


async def async_main():
    # work1 = asyncio.create_task(demo_led())
    work2 = asyncio.create_task(read_message())
    await asyncio.gather(work2)

def main():
    network.init_mqtt_client()
    network_info = network.get_ip()
    print(network_info.get('ip'))
    asyncio.run(async_main())
if __name__ == '__main__':
    main()
    # network.demo_send_message('AT+MQTTLONGCLIENTID?')

